<template>
  <el-dialog :title="`${form.bsChkitemId ? '修改' : '添加'}关联检查项`" :visible.sync="show" :close-on-click-modal="false" :show-close="!btnLoading" width="800px" @closed="$refs.form.resetFields()">
    <el-form ref="form" v-loading="formLoading" :model="form" inline :rules="rules" label-width="100px">
      <el-form-item prop="bsChkitemId" class="hide" />
      <el-form-item label="检查项版本" prop="chkitemVersion" label-width="90px">
        <el-select v-model="form.chkitemVersion" placeholder="请选择检查版本" clearable class="input-item" @change="versionChange">
          <el-option v-for="version in versionList" :key="version.versionCode" :label="version.versionName" :value="version.versionCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="检查项" prop="chkitemCode">
        <treeselect
          v-model="form.chkitemCode"
          :options="chkitemTree"
          no-results-text="暂无数据匹配"
          no-options-text="暂无数据"
          class="input-item"
          :normalizer="normalizer"
          @select="chkitemSelect"
          show-count
          placeholder="请选择检查项"
        />
      </el-form-item>
      <el-form-item label="检查维度" prop="dimension">
        <el-select v-model="form.dimension" placeholder="请选择检查维度" clearable class="input-item">
          <el-option v-for="dict in dict.type.cq_pe_dimension" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="检查方式" prop="generationType">
        <el-select v-model="form.generationType" placeholder="请选择检查方式" clearable class="input-item">
          <el-option v-for="dict in dict.type.cq_pe_generation_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="检查类型" prop="businessType">
        <el-input v-model.trim="form.businessType" placeholder="请输入检查类型名称" :maxlength="255" clearable class="input-item" />
      </el-form-item>
      <el-form-item label="所属系统" prop="belongSystem">
        <el-select v-model="form.belongSystem" placeholder="请选择所属系统" clearable class="input-item">
          <el-option v-for="dict in dict.type.cq_pe_belong_system" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="进入条件" prop="entryCondition">
        <el-select v-model="form.entryCondition" placeholder="请选择进入条件" filterable clearable class="input-item">
          <el-option v-for="dict in funcDictList" :key="dict.dictCode" :label="dict.dictName" :value="dict.dictCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="频次" prop="frequency">
        <div class="frequency-wrap input-item">
          <el-input-number v-model="form.frequency" controls-position="right" :max="1000" :min="1" style="width: 120px;" />
          <span>次</span>
          <span style="font-size: 18px;">/</span>
          <el-select v-model="form.frequencyUnit" placeholder="请选择频次版本" clearable style="width:100px;">
            <el-option v-for="dict in dict.type.cq_pe_frequency_unit" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </div>
      </el-form-item>
      <el-form-item label="退出条件" prop="exitCondition">
        <el-select v-model="form.exitCondition" placeholder="请选择退出条件" filterable clearable class="input-item">
          <el-option v-for="dict in funcDictList" :key="dict.dictCode" :label="dict.dictName" :value="dict.dictCode" />
        </el-select>
      </el-form-item>
      <el-form-item label="最晚时间" prop="latestTimeRule">
        <el-input
          class="input-item"
          placeholder="请输入最晚时间规则"
          v-model="form.latestTimeRule"
        />
      </el-form-item>
      <el-form-item label="类型扩展" prop="businessTypeExpand">
        <el-select v-model="form.businessTypeExpand" placeholder="请选择扩展检查类型" clearable class="input-item">
          <el-option v-for="dict in dict.type.cq_pe_business_type_expand" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="是否统计" prop="isCount">
        <el-switch class="g-switch-in" v-model="form.isCount" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否" :width="50" />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          :rows="2"
          class="input-item"
          placeholder="请输入内容"
          v-model="form.remark"
        />
      </el-form-item>
    </el-form>
    <div slot="footer" style="margin-right: 40px;">
      <el-button type="primary" :loading="btnLoading" @click="btnSubmit">确 定</el-button>
      <el-button :disabled="btnLoading" @click="show = false">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
// 添加或修改检查节点
import { editFormMixin } from '@/utils/mixin'
import { addBsChkitem, updateBsChkitem } from '@/api/cqPe/bsChkitem'
import { listFuncDict } from '@/api/cqPe/funcDict'
import { listVersion } from '@/api/checkScore/cqEval'
import { listChkitem } from '@/api/checkScore/cqEval'
import { flatList2tree } from '@/utils'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  components: { Treeselect },
  mixins: [editFormMixin],
  props: {
    list: {
      type: Array,
      default: () => []
    }
  },
  data() {
    const validateRepeat = (rule, value, callback) => {
      if (this.list.some(item => (item.chkitemCode === value && item.businessTypeExpand === this.form.businessTypeExpand)) && !this.form.bsChkitemId) {
        callback(new Error('检查项已存在，请选择其他检查项'))
      } else {
        callback()
      }
    }
    return {
      primaryKey: 'bsChkitemId',
      addApi: addBsChkitem,
      updateApi: updateBsChkitem,
      form: {
        bsNodeId: '',
        bsChkitemId: '',
        chkitemVersion: '',
        chkitemCode: null,
        businessType: '',
        businessTypeExpand: '', // 检查类型扩展
        belongSystem: '',
        entryCondition: '',
        exitCondition: '',
        latestTimeRule: '',
        frequency: '',
        frequencyUnit: 'YEAR',
        dimension: '',
        generationType: '',
        isCount: 0,
        remark: ''
      },
      rules: {
        chkitemVersion: [{ required: true, message: '请选择检查版本', trigger: 'change' }],
        chkitemCode: [
          { required: true, message: '请选择检查项', trigger: 'change' },
          { validator: validateRepeat, trigger: 'change' }
        ],
        businessType: [{ required: true, message: '请输入检查类型名称', trigger: 'blur' }],
        belongSystem: [{ required: true, message: '请选择所属系统', trigger: 'change' }],
        // entryCondition: [{ required: true, message: '请选择进入条件', trigger: 'change' }],
        // exitCondition: [{ required: true, message: '请选择退出条件', trigger: 'change' }],
        frequency: [{ required: true, message: '请选择周期', trigger: 'change' }],
        dimension: [{ required: true, message: '请选择检查维度', trigger: 'change' }],
        generationType: [{ required: true, message: '请选择检查方式', trigger: 'change' }]
      },
      funcDictList: [],
      versionList: [],
      chkitemTree: [],
      formLoading: false
    }
  },
  watch: {
    'form.chkitemCode'() {
      this.$refs.form.validateField('chkitemCode')
    }
  },
  dicts: ['cq_random_type', 'cq_pe_business_type', 'cq_pe_business_type_expand', 'cq_pe_frequency_unit', 'cq_pe_belong_system', 'cq_pe_generation_type', 'cq_pe_dimension'],
  created() {
    this.getFuncDictList()
    this.getVesionList()
  },
  methods: {
    opened(item) {
      if (item?.frequencyUnit === null) this.form.frequencyUnit = 'EMPTY'
    },
    // 关联检查项 改变
    chkitemSelect(node) {
      if (node.isBussCount || node.isCityCount || node.isProjectCount) {
        this.form.isCount = 1
      } else {
        this.form.isCount = 0
      }
    },
    // 获取方法字典
    async getFuncDictList() {
      this.formLoading = true
      const res = await listFuncDict({pageNum: 1, pageSize: 1000}).catch(() => false)
      this.formLoading = false
      if (res === false) return
      this.funcDictList = res.rows || []
      this.funcDictList.sort((obj1, obj2) => {
        return obj1.dictName.localeCompare(obj2.dictName)
      })
    },
    // 获取版本列表
    async getVesionList() {
      this.formLoading = true
      const res = await listVersion({pageNum: 1, pageSize: 1000}).catch(() => false)
      this.formLoading = false
      if (res === false) return
      this.versionList = res.data || []
      if (this.versionList.length > 0 && this.versionList[0].versionCode) {
        const version = this.versionList.find(item => item.isEnable === 1)
        if (version) {
          this.form.chkitemVersion = version.versionCode
          this.getChkitemList(version.versionCode)
        }
      }
    },
    versionChange(versionCode) {
      if (!versionCode) return
      this.getChkitemList(versionCode)
    },
    normalizer(node) {
      if (!node.children?.length) delete node.children
      return { id: node.chkitemCode, label: node.chkitemName, children: node.children }
    },
    // 检查项列表
    async getChkitemList(versionCode) {
      const opt = { versionCode }
      this.formLoading = true
      const res = await listChkitem(opt).catch(() => false)
      this.formLoading = false
      if (res === false) return
      let data = res.data || []
      if (!data.some(item => item.chkitemCode === this.form.chkitemCode)) {
        this.form.chkitemCode = null
      }
      data = flatList2tree(data, { id: 'chkitemId' })
      this.chkitemTree = data
    }
  }
}
</script>
<style scoped lang="scss">
  .input-item {
    width: 260px;
  }
  .frequency-wrap {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
</style>
